import os
import requests
import tarfile
import tempfile
from django.core.management.base import BaseCommand
from django.conf import settings

class Command(BaseCommand):
    help = '下载 Editor.js 及其插件到静态目录'

    def __init__(self):
        super().__init__()
        # 使用淘宝 CDN
        npm_cdn = "https://registry.npmmirror.com/@editorjs"
        self.packages = {
            'editor': {
                'url': f'{npm_cdn}/editorjs/download/editorjs-2.28.2.tgz',
                'js_path': 'package/dist/editorjs.mjs'
            },
            'header': {
                'url': f'{npm_cdn}/header/download/header-2.8.1.tgz',
                'js_path': 'package/dist/header.mjs'
            },
            'list': {
                'url': f'{npm_cdn}/list/download/list-1.9.0.tgz',
                'js_path': 'package/dist/list.mjs'
            },
            'checklist': {
                'url': f'{npm_cdn}/checklist/download/checklist-1.6.0.tgz',
                'js_path': 'package/dist/checklist.mjs'
            },
            'quote': {
                'url': f'{npm_cdn}/quote/download/quote-2.6.0.tgz',
                'js_path': 'package/dist/quote.mjs'
            },
            'code': {
                'url': f'{npm_cdn}/code/download/code-2.9.0.tgz',
                'js_path': 'package/dist/code.mjs'
            },
            'image': {
                'url': f'{npm_cdn}/image/download/image-2.9.0.tgz',
                'js_path': 'package/dist/image.mjs'
            },
            'link': {
                'url': f'{npm_cdn}/link/download/link-2.6.2.tgz',
                'js_path': 'package/dist/link.mjs'
            },
            'marker': {
                'url': f'{npm_cdn}/marker/download/marker-1.4.0.tgz',
                'js_path': 'package/dist/marker.mjs'
            },
            'table': {
                'url': f'{npm_cdn}/table/download/table-2.3.0.tgz',
                'js_path': 'package/dist/table.mjs'
            },
        }

    def download_and_extract(self, url, js_path, target_path):
        """下载并解压 tgz 文件"""
        try:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            
            with tempfile.NamedTemporaryFile(suffix='.tgz', delete=False) as temp_file:
                temp_file.write(response.content)
                temp_file_path = temp_file.name

            try:
                with tarfile.open(temp_file_path, 'r:gz') as tar:
                    # 打印压缩包内的文件列表，帮助调试
                    self.stdout.write("压缩包内文件列表:")
                    for member in tar.getmembers():
                        self.stdout.write(f"- {member.name}")
                    
                    # 尝试找到正确的文件路径
                    correct_path = None
                    for member in tar.getmembers():
                        if member.name.endswith(js_path.split('/')[-1]):
                            correct_path = member.name
                            break
                    
                    if correct_path is None:
                        raise Exception(f'找不到匹配的文件: {js_path}')
                    
                    # 从压缩包中提取文件
                    js_file = tar.extractfile(correct_path)
                    if js_file is None:
                        raise Exception(f'无法提取文件: {correct_path}')
                    
                    # 保存到目标路径
                    with open(target_path, 'wb') as f:
                        f.write(js_file.read())
                
                return True
            finally:
                os.unlink(temp_file_path)
                
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'处理失败: {str(e)}'))
            return False

    def handle(self, *args, **options):
        # 确定存放目录
        static_dir = os.path.join(settings.BASE_DIR, 'static', 'js', 'editorjs')
        if not os.path.exists(static_dir):
            os.makedirs(static_dir)
            
        success_count = 0
        total_count = len(self.packages)
        
        # 下载并解压每个包
        for name, package_info in self.packages.items():
            file_name = f'{name}.js'
            file_path = os.path.join(static_dir, file_name)
            
            self.stdout.write(f'正在处理 {file_name}...')
            if self.download_and_extract(package_info['url'], package_info['js_path'], file_path):
                success_count += 1
                self.stdout.write(self.style.SUCCESS(f'成功处理 {file_name}'))
            
        # 输出总结
        self.stdout.write('\n处理总结:')
        self.stdout.write(self.style.SUCCESS(f'成功处理 {success_count} 个文件'))
        if success_count < total_count:
            self.stdout.write(self.style.WARNING(f'失败 {total_count - success_count} 个文件'))